package com.cheyunkeji.er.activity.fast_evaluate;

import android.content.Intent;
import android.text.TextUtils;
import android.view.View;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.cheyun.netsalev3.R;
import com.cheyunkeji.er.Constants;
import com.cheyun.netsalev3.MyApplication;
import com.cheyunkeji.er.adapter.fastevaluate.CarModelLvAdapter;
import com.cheyunkeji.er.base.BaseActivity;
import com.cheyunkeji.er.bean.fast_evaluate.CarModel;
import com.cheyunkeji.er.bean.fast_evaluate.CarModelTitle;
import com.cheyunkeji.er.bean.fast_evaluate.CarSeries;
import com.cheyunkeji.er.http.ApiClient;
import com.cheyunkeji.er.http.HttpConstants;
import com.cheyunkeji.er.http.RespCallback;
import com.cheyunkeji.er.view.SToast;
import com.cheyunkeji.er.view.TopBar;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import okhttp3.Request;

public class FastEvaluateCarModelSelectActivity extends BaseActivity implements AdapterView.OnItemClickListener {


    @BindView(R.id.v_topbar)
    TopBar vTopbar;
    @BindView(R.id.tv_car_series)
    TextView tvCarSeries;
    @BindView(R.id.lv_car_model_list)
    ListView lvCarModelList;
    @BindView(R.id.activity_fast_evaluate_car_model_select)
    LinearLayout activityFastEvaluateCarModelSelect;

    @BindView(R.id.ll_car_model_tip)
    LinearLayout ll_car_model_tip;
    @BindView(R.id.tv_car_model_vv)
    TextView tv_car_model_vv;

    private String model_mark;

    private CarSeries selectedCarSeries;

    private ArrayList<CarModel> carModels;

    //   键为汽车款式年份String字符串（如2014），值为保存该年份下所有车型的List集合
    private Map<String, List<CarModel>> yearCarModelListMap;

    private ArrayList<String> yearList;

    private ArrayList<Object> processedDataList;

    private CarModelLvAdapter adapter;

    private String from = "";
    @Override
    protected void init() {

        setContentView(R.layout.er_activity_fast_evaluate_car_model_select);
        ButterKnife.bind(this);

        if(getIntent().hasExtra("from")) {
            from = getIntent().getStringExtra("from");
        }

        selectedCarSeries = (CarSeries) getIntent().getSerializableExtra(Constants.SELECTED_CAR_SERIES_NAME);

        loadCarModels();

        yearList = new ArrayList<>();
        yearCarModelListMap = new HashMap<>();

    }

    /**
     * 将获取的所有车型列表数据按照款式年限进行拆分，生成一个包含两种类型的Adapter填充至ListView中
     * 再根据ListView的Item的Type判断是否处理点击事件，如标题项不处理点击事件，车型项处理点击事件
     */
    private void processRawData() {

        for (int i = 0; i < carModels.size(); i++) {

            CarModel carInfo = carModels.get(i);
//           截取前四个字符获取年限
            String year = carInfo.getName().substring(0, 4);

            if (!yearList.contains(year)) {
                yearList.add(year);
                yearCarModelListMap.put(year, new ArrayList<CarModel>());
            }

            yearCarModelListMap.get(year).add(carInfo);
        }

        List keyList = new ArrayList(yearCarModelListMap.keySet());

        Collections.sort(keyList, new MyComparator());

        processedDataList = new ArrayList<>();

        for (int i = 0; i < keyList.size(); i++) {

            processedDataList.add(new CarModelTitle((String) keyList.get(i) + "款"));

            processedDataList.addAll(yearCarModelListMap.get(keyList.get(i)));
        }

        adapter = new CarModelLvAdapter(processedDataList, this);

        lvCarModelList.setAdapter(adapter);

        lvCarModelList.setOnItemClickListener(this);

    }

    @Override
    protected void initView() {

        vTopbar.setTitle("选择车型");
        vTopbar.setLeftBack();

        tvCarSeries.setText(selectedCarSeries.getName());
        if(getIntent().hasExtra("Mark")){
            model_mark = getIntent().getStringExtra("Mark");
        }
        if (!TextUtils.isEmpty(model_mark)){
            ll_car_model_tip.setVisibility(View.VISIBLE);
            tv_car_model_vv.setText(model_mark);
        }
    }

    @Override
    protected void initData() {

    }

    public void loadCarModels() {

        HashMap<String, String> params = new HashMap<>();
//        params.put("authkey", UserInfoManager.getInstance(MyApplication.getInstance()).getAuthKey());
//        params.put(ChannelInfoUtil.getCurrentChannelInfo().getCkey1().getYkey(), ChannelInfoUtil.getCurrentChannelInfo().getCkey1().getY7e_e73a691f02a46500201c3998e6a2989d());
        params.put("seriesId", selectedCarSeries.getId());

        ApiClient.postForm(HttpConstants.CAR_300_MODELS_LIST, params, new RespCallback<List<CarModel>>() {
            @Override
            protected void onRequestFailed(String msg) {
                SToast.show(msg);
            }

            @Override
            protected void onSuccess(List<CarModel> data) {

                carModels = (ArrayList<CarModel>) data;

                if (null != carModels && carModels.size() != 0) {
                    processRawData();
                }

            }

            @Override
            public void onBefore(Request request, int id) {
                showDialog();
            }

            @Override
            public void onAfter(int id) {
                dismissDialog();
            }


        });

    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

        if (processedDataList.get(position) instanceof CarModel) {
            Intent intent = new Intent(this,FastEvaluateActivity.class);
            intent.putExtra("aaaa","ddddd");
            intent.putExtra(Constants.SELECTEDCAR_MODEL_OBJECT,((CarModel) processedDataList.get(position)));
            intent.putExtra("from",from);
            startActivity(intent);
            //startActivity(new Intent(FastEvaluateCarModelSelectActivity.this,FastEvaluateActivity.class).putExtra(Constants.SELECTEDCAR_MODEL_OBJECT,((CarModel) processedDataList.get(position))));
            MyApplication.getInstance().getCar300Ids().setCarModelId( ((CarModel) processedDataList.get(position)).getId());
        }

    }

    private class MyComparator implements java.util.Comparator {

        @Override
        public int compare(Object o1, Object o2) {

            String a = (String) o1;
            String b = (String) o2;


            return (Integer.valueOf(b) - Integer.valueOf(a));

//            return Integer.valueOf(a).compareTo(Integer.valueOf(b));
        }
    }


}
